import 'package:aweb5/Constants.dart';
import 'package:aweb5/generated/json/share_all_entity_helper.dart';
import 'package:aweb5/generated/json/share_cash_entity_helper.dart';
import 'package:aweb5/generated/json/share_hongbao_entity_helper.dart';
import 'package:aweb5/generated/json/share_material_entity_helper.dart';
import 'package:aweb5/pages/AplusLoginWithPhone.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/base/BaseWidget.dart';

import 'package:aweb5/util/WindowUtil.dart';

import 'package:badges/badges.dart';

import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/services.dart';
import 'dart:io';

import 'dart:async';
import 'dart:convert';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/config/Config.dart';
import 'dart:convert';
import 'package:aweb5/util/FileUtil.dart';
import 'package:aweb5/util/fluwxUtil.dart';
import 'package:aweb5/bean/link_entity.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:dio/dio.dart';
import 'package:aweb5/bean/wxpay_entity.dart';
import 'package:aweb5/bean/aplus/share_hongbao_entity.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import 'package:aweb5/bean/aplus/share_material_entity.dart';

import 'package:permission_handler/permission_handler.dart';

import 'package:aweb5/util/PermissionUtil.dart';
import 'package:load/load.dart';
//import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:aweb5/config/StoreStatic.dart';
import 'package:aweb5/util/SharedUtil.dart';
import 'package:aweb5/util/HttpUtils1.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:aweb5/bean/aplus/share_all_entity.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:aweb5/bean/aplus/member_info_entity.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';

import 'package:amap_core_fluttify/amap_core_fluttify.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import 'dart:io' as H;
import 'package:aweb5/pages/transit_page.dart';
import 'AplusLoginPage.dart';
import 'package:aweb5/bean/downloadbean.dart';
import 'package:aweb5/bean/aplus/share_cash_entity.dart';
class HomePage extends BaseWidget {
  String memberid = "";
  HomePage(this.memberid);
  @override
  State<HomePage> createState() => HomePageState();
}

class HomePageState extends BaseWidgetState<HomePage> {
  int currentTab = 0;
  int shoppongNum = 0;
  DateTime lastPopTime;
  JPush jpush = new JPush();
  double width;
  WebViewController controller;
  int index = 0;
  bool firstPage = true;

//  double lat = 0;
//  double lng = 0;
  Dio dio;

  int memberid = 1;

  Widget body = Scaffold();
  BuildContext context;

  bool iscenter = false;
  ProgressDialog pr;

  ShareAllEntity linkEntity;

  String _result = "无";
  String _url = "https://wxpay.wxutil.com/pub_v2/app/app_pay.php";
  String videopath = "";
  @override
  void initState() {
    super.initState();

    WindowUtil.setStatusBar(Colors.white, true);

//    fluwxUtil.init("wx8d3746380a937886", "");
    Map<String, String> map = Map();
    map["j"] = "1";
    map["a"] = "2";
    map["f"] = "3";
    map["g"] = "4";
    fluwxUtil.wxpay_md5(map);

    WidgetsBinding.instance.addPostFrameCallback((_) {
//      showBottomShareDialog(context);

    Future.delayed(Duration(seconds: 5),(){setJpush();});

    });
    fluwx.weChatResponseEventHandler.listen((res) {
      if (res is fluwx.WeChatPaymentResponse) {
        setState(() {
          _result = "pay :${res.isSuccessful}";
        });
      }
    });

    amap();
    handleFirstPage();
//    String basicpath = (await FileUtil.findLocalPath(context)) +
//        Constants.savePath;

    FileUtil.findLocalPath(context).then((value) {
    FileUtil.clearDirect(value, context);
    });


  }

  void _wechatPay() async {
    var h = H.HttpClient();
    h.badCertificateCallback = (cert, String host, int port) {
      return true;
    };
    var request = await h.getUrl(Uri.parse(_url));
    var response = await request.close();
    var data = await Utf8Decoder().bind(response).join();
    Map<String, dynamic> result = json.decode(data);
    print(result['appid']);
    print(result["timestamp"]);
    fluwx
        .payWithWeChat(
      appId: result['appid'].toString(),
      partnerId: result['partnerid'].toString(),
      prepayId: result['prepayid'].toString(),
      packageValue: result['package'].toString(),
      nonceStr: result['noncestr'].toString(),
      timeStamp: result['timestamp'],
      sign: result['sign'].toString(),
    )
        .then((data) {
      print("---》$data");
    });
  }

  Future<bool> requestPermission() async {
    PermissionStatus status =
        await PermissionUtil.requestPermission(Permission.location);
//    final permissions =
//    await PermissionHandler().requestPermissions([PermissionGroup.location]);

    if (status == PermissionStatus.granted) {
      return true;
    } else {
      toast('需要定位权限!');
      return false;
    }
  }

//  116.23128    40.22077
  Location _location;
  double lng = 0; //经度
  double lat = 0; //维度
  bool finished = false;
  bool setlat = false;
  void amap() async {
    /// !注意: 只要是返回Future的方法, 一律使用`await`修饰, 确保当前方法执行完成后再执行下一行, 在不能使用`await`修饰的环境下, 在`then`方法中执行下一步.
    /// 初始化 iOS在init方法中设置, android需要去AndroidManifest.xml里去设置, 详见 https://lbs.amap.com/api/android-sdk/gettingstarted
    await AmapCore.init('00b6ff0d3d124c2510a850605edba4c8');

// 单次定位

    if (Platform.isAndroid) {
      if (await requestPermission()) {
        final location = await AmapLocation.instance.fetchLocation();
        lng = location.latLng.longitude;
        lat = location.latLng.latitude;
//      Fluttertoast.showToast(msg: "${lat}");
        if (finished && !setlat) {
          setlat = true;
          controller
              ?.evaluateJavascript('latLng("${lng},${lat}")')
              ?.then((result) {
            // You can handle JS result here.
          });
        }

//      setState(() {
//
//        lng = location.latLng.longitude;
//        lat = location.latLng.latitude;
//
//      });
      }
    } else {
      final location = await AmapLocation.instance.fetchLocation();
      lng = location.latLng.longitude;
      lat = location.latLng.latitude;
//      Fluttertoast.showToast(msg: "${lat}");
      if (finished && !setlat) {
        setlat = true;
        controller
            ?.evaluateJavascript('latLng("${lng},${lat}")')
            ?.then((result) {
          // You can handle JS result here.
        });
      }

//      setState(() {
//
//        lng = location.latLng.longitude;
//        lat = location.latLng.latitude;
//
//      });

    }

// 连续定位
//    if (await requestPermission()) {
//    AmapLocation.instance.listenLocation()
//        .listen((location) => setState(() => _location = location));
//    }
  }

  @override
  Widget build(BuildContext context) {
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>build");
    initDialog(context);
    this.context = context;
    WindowUtil.window_width = MediaQuery.of(context).size.width;
    WindowUtil.statusbar_height = MediaQuery.of(context).padding.top;
    init(context);

    return buildBody();
  }

  showBottomShareDialog(BuildContext context) {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        isScrollControlled: true,
        builder: (con) {
          return bottomSheetWidget();
        });
  }

  showBottomShareSucai(){
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        isScrollControlled: true,
        builder: (con) {
          return bottomSheetWidget();
        });
  }

  Widget bottomShareSucai(){

    return Container(
      height: 300,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20), topRight: Radius.circular(20))),
      padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              GestureDetector(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.white,
                      radius: 26.0,
                      backgroundImage: AssetImage("assets/weixin1.png"),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Text("微信好友")
                  ],
                ),
                onTap: () {
                  fluwxUtil.shareMiniProToSession(
                      linkEntity.link,
                      Config.mini,
                      linkEntity.title,
                      linkEntity.smallPath,
                      linkEntity.desc,
                      linkEntity.smallShareImg);
                },
              ),
              Spacer(),
              GestureDetector(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.white,
                      radius: 26.0,
                      backgroundImage: AssetImage("assets/erweima.png"),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Text("二维码海报")
                  ],
                ),
                onTap: () {
                  shareProductToSession();
                },
              ),
              Spacer(),
              GestureDetector(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.white,
                      radius: 26.0,
                      backgroundImage: AssetImage("assets/lianjie1.png"),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Text("复制链接")
                  ],
                ),
                onTap: () {
                  copyLink();
                },
              ),
              Spacer(),
              GestureDetector(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.white,
                      radius: 26.0,
                      backgroundImage: AssetImage("assets/web.png"),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Text("分享链接")
                  ],
                ),
                onTap: () {
                  shareWebToSession();
                },
              ),
            ],
          ),
          SizedBox(
            height: 50,
          ),
          GestureDetector(
            child: Container(
              margin: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5), color: Colors.red),
              width: 200,
              height: 35,
              child: Center(
                child: Text(
                  "取消",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            onTap: () {
              NaviUtil.pop(context);
            },
          )
        ],
      ),
    );

  }


  Widget bottomSheetWidget() {
    if (Constants.memberInfoEntity.data.isGroup == 1) {
      return Container(
        height: 350,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20), topRight: Radius.circular(20))),
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/weixin1.png"),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Text("微信")
                    ],
                  ),
                  onTap: () {
                    fluwxUtil.shareMiniProToSession(
                        linkEntity.link,
                        Config.mini,
                        linkEntity.title,
                        linkEntity.smallPath,
                        linkEntity.desc,
                        linkEntity.smallShareImg);
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/erweima.png"),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Text("二维码海报")
                    ],
                  ),
                  onTap: () {
                    shareProductToSession();
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/lianjie1.png"),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Text("复制链接")
                    ],
                  ),
                  onTap: () {
                    copyLink();
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/yaoqing.png"),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Text("邀请顾客")
                    ],
                  ),
                  onTap: () {
                    shareInviteWebToSession();
                  },
                ),
              ],
            ),
            SizedBox(
              height: 25,
            ),
            Row(
              children: <Widget>[
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/web.png"),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Text("分享链接")
                    ],
                  ),
                  onTap: () {
                    shareWebToSession();
                  },
                ),
                Spacer(),
              ],
            ),
            SizedBox(
              height: 35,
            ),
            GestureDetector(
              child: Container(
                margin: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5), color: Colors.red),
                width: 200,
                height: 35,
                child: Center(
                  child: Text(
                    "取消",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
              onTap: () {
                NaviUtil.pop(context);
              },
            )
          ],
        ),
      );
    } else {
      return Container(
        height: 300,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20), topRight: Radius.circular(20))),
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/weixin1.png"),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text("微信")
                    ],
                  ),
                  onTap: () {
                    fluwxUtil.shareMiniProToSession(
                        linkEntity.link,
                        Config.mini,
                        linkEntity.title,
                        linkEntity.smallPath,
                        linkEntity.desc,
                        linkEntity.smallShareImg);
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/erweima.png"),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text("二维码海报")
                    ],
                  ),
                  onTap: () {
                    shareProductToSession();
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/lianjie1.png"),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text("复制链接")
                    ],
                  ),
                  onTap: () {
                    copyLink();
                  },
                ),
                Spacer(),
                GestureDetector(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 26.0,
                        backgroundImage: AssetImage("assets/web.png"),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text("分享链接")
                    ],
                  ),
                  onTap: () {
                    shareWebToSession();
                  },
                ),
              ],
            ),
            SizedBox(
              height: 50,
            ),
            GestureDetector(
              child: Container(
                margin: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5), color: Colors.red),
                width: 200,
                height: 35,
                child: Center(
                  child: Text(
                    "取消",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
              onTap: () {
                NaviUtil.pop(context);
              },
            )
          ],
        ),
      );
    }
  }

  initDialog(BuildContext context) {
    pr = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      textDirection: TextDirection.rtl,
      isDismissible: true,
    );

    pr.style(
//      message: 'Downloading file...',
      message: "请稍候……",
      borderRadius: 10.0,
      backgroundColor: Colors.white,
      elevation: 10.0,
      insetAnimCurve: Curves.easeInOut,
      progress: 0.0,
      progressWidgetAlignment: Alignment.center,
      maxProgress: 100.0,
      progressTextStyle: TextStyle(
          color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
      messageTextStyle: TextStyle(
          color: Colors.black, fontSize: 19.0, fontWeight: FontWeight.w600),
    );
  }



  Widget buildBody() {
    print(">>>1");

    return WillPopScope(
        child: Scaffold(
          floatingActionButton: GestureDetector(
            onTap: () {
              controller
                  ?.evaluateJavascript(
                      'sendmemberid("${Constants.memberInfoEntity.data.memberId}")')
                  ?.then((result) {
//                // You can handle JS result here.
              });
              controller?.evaluateJavascript('flutter("${2}")')?.then((result) {
                // You can handle JS result here.
              });

              currentTab = 100;
              setState(() {});
            },
            child: Container(
              width: firstPage ? 54 : 0,
              height: 54,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(50),
                child: FadeInImage.assetNetwork(
                  width: 50,
                  height: firstPage ? 50 : 0,
                  placeholder: 'assets/touxiang.png',
                  image: Constants.memberInfoEntity?.data.headimgurl,
                  fit: BoxFit.cover,
                ),
              ),
              decoration: BoxDecoration(
                  color: Color(0xffce2020),
                  borderRadius: BorderRadius.circular(50)),
              alignment: Alignment.center,
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
          body: getPage(),
          bottomNavigationBar:
//            bottom3()

              bottomAppBar(),
        ),
        onWillPop: () {
          controller.currentUrl().then((String v) {
            if (isFirstPage(v)) {
              if (lastPopTime == null ||
                  DateTime.now().difference(lastPopTime) >
                      Duration(seconds: 2)) {
                lastPopTime = DateTime.now();
                Fluttertoast.showToast(msg: "再按一次退出");
              } else {
                lastPopTime = DateTime.now();
                // 退出app
                SystemChannels.platform.invokeMethod('SystemNavigator.pop');
              }
            } else {
              controller.canGoBack().then((v) {
                if (v) {
                  controller.goBack();
                } else {
                  if (lastPopTime == null ||
                      DateTime.now().difference(lastPopTime) >
                          Duration(seconds: 2)) {
                    lastPopTime = DateTime.now();
                    Fluttertoast.showToast(msg: "再按一次退出");
                  } else {
                    lastPopTime = DateTime.now();
                    // 退出app
                    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
                  }
                }
              });
            }
          });
        });
  }

  //底部tab
  Widget bottomAppBar() {
    return Visibility(
        visible: firstPage,
        child: BottomAppBar(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 6, 0, 6),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");

                      iscenter = false;
                      index = 0;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});
//                      controller.loadUrl("https://a.91aplus.com/#/member");
                      controller
                          ?.evaluateJavascript('flutter("${index}")')
                          ?.then((result) {});
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(0), getTitle1(0)],
                    )),
                GestureDetector(
                    onTap: () {
                      index = 1;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      controller
                          ?.evaluateJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(1), getTitle1(1)],
                    )),
                GestureDetector(
                  onTap: () {
                    currentTab = 100;
                    controller
                        ?.evaluateJavascript('flutter("${2}")')
                        ?.then((result) {
                      // You can handle JS result here.
                    });
                    setState(() {});
                  },
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        Icons.home,
                        color: Colors.transparent,
                      ),
                      Text("个人中心", style: TextStyle(color: centerColor()))
                    ],
                  ),
                ),
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");
                      index = 3;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      controller
                          ?.evaluateJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(3), getTitle1(3)],
                    )),
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");
                      index = 4;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      controller
                          ?.evaluateJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(4), getTitle1(4)],
                    ))
              ],
            ),
          ),
        ));
  }

  Color centerColor() {
    if (currentTab == 100) {
      return Color(0xffce2020);
    } else {
      return Color(0xff100f0f);
    }
  }

  //是否是第一页
  bool isFirstPage(String v) {
    if (v == ("${Config.baseUrl}#/login") ||
        v.startsWith("${Config.baseUrl}#/classify") ||
        v == ("${Config.baseUrl}#/") ||
        v.startsWith("${Config.baseUrl}#/member") ||
        v.startsWith("${Config.baseUrl}#/cart") ||
        v == ("${Config.baseUrl}#/order") ||
        v.startsWith("${Config.baseUrl}#/?kk=2")) {
      return true;
    } else {
      return false;
    }
  }

  Future cango() async {
    bool can = await controller.canGoBack();
    return can;
  }

  void tap1() {
    //  toast("${index}");

    currentTab = index;
    if (index > 2) {
      //currentTab--;
    }
    setState(() {});

    controller?.evaluateJavascript('flutter("${index}")')?.then((result) {
      // You can handle JS result here.
    });
    print(">>>>${index}");
  }

  Widget getPage() {
    return SafeArea(
        child: Stack(
      children: <Widget>[
        WebView(
          userAgent: "flutter",
          initialUrl: Config.baseUrl,
          javascriptMode: JavascriptMode.unrestricted,
          onPageStarted: (v) {
            print("currentPage>>>${v}");
          },
          onPageFinished: (v) {
            print("currentPage>>>${v}");
            print(
                "sendmemberid>>>>${Constants.memberInfoEntity.data.memberId}");

            controller?.evaluateJavascript(
                'sendmemberid("${Constants.memberInfoEntity.data.memberId}")');

            if (lat != 0 && !setlat) {
              setlat = true;
              controller
                  ?.evaluateJavascript('latLng("${lng},${lat}")')
                  ?.then((result) {
                // You can handle JS result here.
              });
            }

//            setJpush();
            if (v.startsWith(Config.baseUrl)) {
              if (!v.startsWith("${Config.baseUrl}#/classify") &&
                  v != ("${Config.baseUrl}#/") &&
                  !v.startsWith("${Config.baseUrl}#/member") &&
                  !v.startsWith("${Config.baseUrl}#/cart") &&
                  v != ("${Config.baseUrl}#/order") &&
                  v != ("${Config.baseUrl}#/?kk=2")) {
                firstPage = false;
              } else {
                firstPage = true;
              }

              if (v == ("${Config.baseUrl}#/")) {
                currentTab = 0;
              }
              if (v.startsWith("${Config.baseUrl}#/cart")) {
                currentTab = 3;
              }
              if (v == ("${Config.baseUrl}#/?kk=2")) {
                currentTab = 0;
              }
              if (v.startsWith("${Config.baseUrl}#/order")) {
                currentTab = 4;
              }
              setState(() {});

              width = 0;
              controller.currentUrl().then((v) {
                print("currentPage>>>${v}");
              });

              // _initLocation();
              setState(() {});
            }
          },
          onWebViewCreated: (WebViewController web) {
            controller = web;
          },
          navigationDelegate: (request) {

            print("currentPage>>>${request.url}");

            var v = request.url;

            if (v.startsWith(Config.baseUrl)) {
              if (!v.startsWith("${Config.baseUrl}#/classify") &&
                  v != ("${Config.baseUrl}#/") &&
                  !v.startsWith("${Config.baseUrl}#/member") &&
                  !v.startsWith("${Config.baseUrl}#/cart") &&
                  v != ("${Config.baseUrl}#/order") &&
                  v != ("${Config.baseUrl}#/?kk=2")) {
                firstPage = false;
              } else {
                firstPage = true;
              }

              if (v.contains("payComplete")) {
                firstPage = false;
              }
              if (v.startsWith("${Config.baseUrl}#/orderInfo")) {
                firstPage = false;
              }

              if (v == ("${Config.baseUrl}#/")) {
                currentTab = 0;
              }
              if (v.startsWith("${Config.baseUrl}#/cart")) {
                currentTab = 3;
              }
              if (v == ("${Config.baseUrl}#/?kk=2")) {
                currentTab = 0;
              }
              if (v.startsWith("${Config.baseUrl}#/order")) {
                currentTab = 4;
              }
              setState(() {});

              width = 0;
              controller.currentUrl().then((v) {
                print("currentPage>>>${v}");
              });

              // _initLocation();
              setState(() {});
            }

            if (v.startsWith("weixin")) {
              canLaunch(v).then((value) {
                if (value) {
                  launch(v);
                } else {
                  toast("发起微信支付异常");
                }
              });

              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
          javascriptChannels: <JavascriptChannel>[
            _alertJavascriptChannel7(),
            _alertJavascriptChannel2(),
            _alertJavascriptChannel3(),
            _alertJavascriptChannel4(),
            _alertJavascriptChannel5(),
            _alertJavascriptChannel6(),
            _alertJavascriptChannel9(),
            _alertJavascriptChannel10(),
            _alertJavascriptChannel101(),
            _alertJavascriptChannel102(),
            _alertJavascriptChannel103(),
            _alertJavascriptChannel33(),
          ].toSet(),
        ),
      ],
    ));
  }

  callback(shopNum) {
    shoppongNum = shopNum;
    setState(() {});
  }

  void handleFirstPage(){
    Timer.periodic(Duration(milliseconds: 100), (v){
      if(Platform.isIOS){

         controller?.currentUrl().then((value){
           if(this.firstPage!=isFirstPage(value)){

             this.firstPage = isFirstPage(value);
             setState(() {

             });

           }
           ;
         });

      }
    });

  }

  Widget bage() {
    return Opacity(
      opacity: shoppongNum == 0 ? 0.0 : 1.0,
      child: Badge(
        position: BadgePosition(top: 0, right: 0),

        badgeColor: Colors.red,
        shape: BadgeShape.circle,
//        borderRadius: 10,
        toAnimate: false,
        badgeContent: Text('${shoppongNum}',
            style: TextStyle(color: Colors.white, fontSize: 10)),
      ),
    );
  }

  Widget customBage() {
    return Opacity(
      opacity: shoppongNum == 0 ? 0.0 : 1.0,
      child: Container(
        decoration: BoxDecoration(color: Colors.red, shape: BoxShape.circle),
        padding: EdgeInsets.all(5),
        child: Text('${shoppongNum}',
            style: TextStyle(color: Colors.white, fontSize: 10)),
      ),
    );
  }

  Future initStatus() async {}

  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'setTabBarVisible',
        onMessageReceived: (JavascriptMessage message) {});
  }

  JavascriptChannel _alertJavascriptChannel1() {
    return JavascriptChannel(
        name: 'setShopCartNum',
        onMessageReceived: (JavascriptMessage message) {
          try {
            shoppongNum = int.parse(message.message);
          } catch (e) {
            print(">>>set" + e.toString());
          }

          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel2() {
    return JavascriptChannel(
        name: 'setTabSelect',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>messagesettabselect");

          if (message.message == "1") {
            currentTab = 0;
          }
          if (message.message == "2") {
            currentTab = 1;
          }
          if (message.message == "3") {
            currentTab = 2;
          }
          if (message.message == "4") {
            currentTab = 3;
          }
          if (message.message == "5") {
            currentTab = 4;
          }
          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel3() {
//    {"title":"大末老式月饼购买链接",
//    "desc":"甄选阳光面粉等健康原材，六款精配馅料，匠心呈现，传统糕点师傅，手工匠制，当天现做现发，新鲜直达，外皮香甜松软，细腻绵沙，馅料丰富饱满，醇香馥郁，入口香浓递进，甜美不腻！",
//    "link":"https://a.91aplus.com/#/detail/3154/parent_id/476988/share_member_id/476988",
//    "imgUrl":"https://file.91aplus.com/images_8ee5e2020080511432691928.jpg",
//    "smallPath":"/pages/detail/detail?parent_id=476988&goods_id=3154",
//    "smallShareImg":"https://file.91aplus.com/group_poster_images_be8bf2020082120094318478.png",
//    "joinLink":"https://a.91aplus.com/#/iwrite/3/476988",
//    "codeImgUrl":"https://file.91aplus.com/group_poster_images_875252020082120094326963.png"}

    return JavascriptChannel(
        name: 'shareLinkToSession',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(message.message);

          try {
            Map<String, dynamic> map =
                JsonUtil.json2map(message.message.toString());

            print(">>>map${map["title"]}");
            linkEntity = ShareAllEntity();
            linkEntity = shareAllEntityFromJson(linkEntity, map);
            print(">>>>>${linkEntity.imgUrl}");
            print("share>>>>>${linkEntity.link}");

            showBottomShareDialog(context);
          } catch (e) {
            print(">>>${e.toString()}");
          }
        });
  }
  JavascriptChannel _alertJavascriptChannel33() {
//    {"title":"大末老式月饼购买链接",
//    "desc":"甄选阳光面粉等健康原材，六款精配馅料，匠心呈现，传统糕点师傅，手工匠制，当天现做现发，新鲜直达，外皮香甜松软，细腻绵沙，馅料丰富饱满，醇香馥郁，入口香浓递进，甜美不腻！",
//    "link":"https://a.91aplus.com/#/detail/3154/parent_id/476988/share_member_id/476988",
//    "imgUrl":"https://file.91aplus.com/images_8ee5e2020080511432691928.jpg",
//    "smallPath":"/pages/detail/detail?parent_id=476988&goods_id=3154",
//    "smallShareImg":"https://file.91aplus.com/group_poster_images_be8bf2020082120094318478.png",
//    "joinLink":"https://a.91aplus.com/#/iwrite/3/476988",
//    "codeImgUrl":"https://file.91aplus.com/group_poster_images_875252020082120094326963.png"}

    return JavascriptChannel(
        name: 'shareCashToSession',
        onMessageReceived: (JavascriptMessage message) async {
          print(">>>>>>>>message${message.message}");
//          ClipboardData clipboardData = ClipboardData(text: message.message);
//          Clipboard.setData(clipboardData);
//          clearData();
//          NaviUtil.push(context, TransitPaget());
//          NaviUtil.pushAndRemove(context, LoginPage(false));
//          downloadOneImg(message.message);

          Map<String, dynamic> map =
          JsonUtil.json2map(message.message.toString());
          print(message.message);
          ShareCashEntity shareMaterialEntity = new ShareCashEntity();
          shareMaterialEntity =
              shareCashEntityFromJson(shareMaterialEntity, map);
          fluwxUtil.shareLinkToSession(
              shareMaterialEntity.link, shareMaterialEntity.title, shareMaterialEntity.imgUrl, shareMaterialEntity.desc);
        });
  }
  JavascriptChannel _alertJavascriptChannel9() {
    return JavascriptChannel(
        name: 'shareLinkToMini',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(message.message);

          try {
            ClipboardData clipboardData =
                ClipboardData(text: message.toString());
            Clipboard.setData(clipboardData);
            Map<String, dynamic> map =
                JsonUtil.json2map(message.message.toString());

            print(">>>map${map["title"]}");
            ShareHongbaoEntity shareHongbaoEntity;
            shareHongbaoEntity = ShareHongbaoEntity();
            shareHongbaoEntity =
                shareHongbaoEntityFromJson(shareHongbaoEntity, map);
            print(">>>>>${shareHongbaoEntity.imgUrl}");
            print("share>>>>>${shareHongbaoEntity.link}");

            fluwxUtil.shareMiniProToSession(
                shareHongbaoEntity.link,
                Config.mini,
                shareHongbaoEntity.title,
                shareHongbaoEntity.link,
                shareHongbaoEntity.desc,
                shareHongbaoEntity.imgUrl);
//            showBottomShareDialog(context);
          } catch (e) {
            print(">>>${e.toString()}");
          }
        });
  }

  int downloadNum = 0;
  List<bool> finishNum = List();
  List<String> path = new List();
  String tempPath = "testtemp";
  var dialog;

  String nonstaticTempPath = "";
  Map fileImageMap = Map();
  bool notshare1 = false;
  bool sharevideo = false;
  //一键下载
  JavascriptChannel _alertJavascriptChannel4() {
    ///素材下载
    return JavascriptChannel(
        name: 'shareMaterialToSession',
        onMessageReceived: (JavascriptMessage message) async {
          print(">>>>>>>>message${message.message}");
//          ClipboardData clipboardData = ClipboardData(text: message.message);
////          Clipboard.setData(clipboardData);
          clearData();
          String basicpath = (await FileUtil.findLocalPath(context)) +
              Constants.savePath;
          final savedDir = Directory(basicpath);
          bool hasExisted = await savedDir.exists();
          if (!hasExisted) {
            savedDir.create();
          }

          videopath ="";
          notshare1 = false;
          sharevideo = false;
          path.clear();
          // toast("${message.message}");
//          Fluttertoast.showToast(msg: message.message);
          Map<String, dynamic> map =
              JsonUtil.json2map(message.message.toString());
          print(message.message);
          ShareMaterialEntity shareMaterialEntity = new ShareMaterialEntity();
          shareMaterialEntity =
              shareMaterialEntityFromJson(shareMaterialEntity, map);

          if(shareMaterialEntity.isDownload=="1"){
            notshare1 =true;
            sharevideo = false;
          }else{




            if(shareMaterialEntity.imgList.length>0){
              notshare1 = false;
              sharevideo = false;
            }else{
              notshare1 = true;
              if(shareMaterialEntity.video.length>0){
                sharevideo = false;
              }

            }

          }

          if (Platform.isAndroid) {
            PermissionStatus status =
                await PermissionUtil.requestPermission(Permission.storage);

            if (status == PermissionStatus.granted) {
              String fileName =
                  DateTime.now().millisecondsSinceEpoch.toString() + ".mp4";

              if (basicpath.isEmpty) {
                print(">>>>basicpathisnull");
              } else {
                print(">>>>basicpath$basicpath");
              }
              if (fileName.isEmpty) {
                print(">>>>fileNameisnull");
              } else {
                print(">>>>fileName$fileName");
              }

              StoreStatic.tempPath =
                  basicpath + Platform.pathSeparator + fileName;
              nonstaticTempPath = basicpath + Platform.pathSeparator + fileName;

              SharedUtil.addStr("tempvideo", nonstaticTempPath);
//            if (tempPath.isEmpty) {
//              print(">>>>tempPathisnull");
//            } else {
//              print(">>>>tempPath$tempPath");
//            }
//            print("${StoreStatic.tempPath}");
              downloadNum = 1;

              print("pathlength>>>>>${path.length}");
//             requestDownload("http://vfx.mtime.cn/Video/2019/03/21/mp4/190321153853126488.mp4",fileName,

              if (shareMaterialEntity.text.isNotEmpty) {
                ClipboardData data = new ClipboardData(
                    text: shareMaterialEntity.text.replaceAll("nsr", "\r\n"));
                Clipboard.setData(data);
                Fluttertoast.showToast(msg: "文案已复制");
                if (shareMaterialEntity.imgList.length == 0&&shareMaterialEntity.video.length==0) {
                  fluwxUtil.shareTextToSession(
                      shareMaterialEntity.text.replaceAll("nsr", "\r\n"));
                }
              }




              List<DownloadBean> downloadList = List();

              for(int i=0;i<shareMaterialEntity.imgList.length;i++){
                downloadList.add(DownloadBean(true, shareMaterialEntity.imgList[i]));
              }
              for(int i=0;i<shareMaterialEntity.video.length;i++){
                downloadList.add(DownloadBean(false, shareMaterialEntity.video[i]));
              }

              if (downloadList.length > 0) {
                downloadNum = downloadList.length;
                if (downloadNum > 0) {
                  await pr.show();
                }





                for (int i = 0; i < downloadList.length; i++) {
                  String savep = basicpath +
                      "${downloadList[i].image?"/${DateTime.now().millisecondsSinceEpoch}x${i}x.jpg":"/${DateTime.now().millisecondsSinceEpoch}x${i}x.mp4"}";

                  if(!downloadList[i].image){

                    videopath = savep;

                  }



                  HttpUtils.downloadImgs(
                      downloadList[i].url,
                      basicpath +
                          "${downloadList[i].image?"/${DateTime.now().millisecondsSinceEpoch}x${i}x.jpg":"/${DateTime.now().millisecondsSinceEpoch}x${i}x.mp4"}"

                          ,
                      path,
                      finishNum,
                      downloadCallBack,
                      downloadNum,
                      pr,
                      i,saveToGallery: shareMaterialEntity.isDownload=="1"?true:false);
                }
              }

//              else
//
//
//                if (shareMaterialEntity.video.length > 0) {
//                String fileName =
//                    DateTime.now().millisecondsSinceEpoch.toString() + ".mp4";
//                tempPath = basicpath + Platform.pathSeparator + fileName;
//
//                path.add(tempPath);
//                downloadNum = 1;
//                await pr.show();
//
//                HttpUtils.downloadVideoFile(shareMaterialEntity.video[0],
//                    nonstaticTempPath, downloadVideoCall, pr);
//              }
            }
          } else {
            String fileName =
                DateTime.now().millisecondsSinceEpoch.toString() + ".mp4";

            if (basicpath.isEmpty) {
              print(">>>>basicpathisnull");
            } else {
              print(">>>>basicpath$basicpath");
            }
            if (fileName.isEmpty) {
              print(">>>>fileNameisnull");
            } else {
              print(">>>>fileName$fileName");
            }

            StoreStatic.tempPath =
                basicpath + Platform.pathSeparator + fileName;
            nonstaticTempPath = basicpath + Platform.pathSeparator + fileName;

            SharedUtil.addStr("tempvideo", nonstaticTempPath);
//            if (tempPath.isEmpty) {
//              print(">>>>tempPathisnull");
//            } else {
//              print(">>>>tempPath$tempPath");
//            }
//            print("${StoreStatic.tempPath}");
            downloadNum = 1;

            print("pathlength>>>>>${path.length}");
//             requestDownload("http://vfx.mtime.cn/Video/2019/03/21/mp4/190321153853126488.mp4",fileName,

            if (shareMaterialEntity.text.isNotEmpty) {
              ClipboardData data = new ClipboardData(
                  text: shareMaterialEntity.text.replaceAll("nsr", "\r\n"));
              Clipboard.setData(data);
              Fluttertoast.showToast(msg: "文案已复制");
              if (shareMaterialEntity.imgList.length == 0&&shareMaterialEntity.video.length==0) {
                fluwxUtil.shareTextToSession(
                    shareMaterialEntity.text.replaceAll("nsr", "\r\n"));
              }
            }
            List<DownloadBean> downloadList = List();

            for(int i=0;i<shareMaterialEntity.imgList.length;i++){
              downloadList.add(DownloadBean(true, shareMaterialEntity.imgList[i]));
            }
            for(int i=0;i<shareMaterialEntity.video.length;i++){
              downloadList.add(DownloadBean(false, shareMaterialEntity.video[i]));
            }

            if (downloadList.length > 0) {
              downloadNum = downloadList.length;
              if (downloadNum > 0) {
                await pr.show();
              }





              for (int i = 0; i < downloadList.length; i++) {

                String savep = basicpath +
                    "${downloadList[i].image?"/${DateTime.now().millisecondsSinceEpoch}x${i}x.jpg":"/${DateTime.now().millisecondsSinceEpoch}x${i}x.mp4"}";

                if(!downloadList[i].image){

                  videopath = savep;

                }


                HttpUtils.downloadImgs(
                    downloadList[i].url,
                    savep

                    ,
                    path,
                    finishNum,
                    downloadCallBack,
                    downloadNum,
                    pr,
                    i,saveToGallery: shareMaterialEntity.isDownload=="1"?true:false);
              }
            }


//            else if (shareMaterialEntity.video.length > 0) {
//              String fileName =
//                  DateTime.now().millisecondsSinceEpoch.toString() + ".mp4";
//              tempPath = basicpath + Platform.pathSeparator + fileName;
//
//              path.add(tempPath);
//              downloadNum = 1;
//              await pr.show();
//
//              HttpUtils.downloadVideoFile(shareMaterialEntity.video[0],
//                  nonstaticTempPath, downloadVideoCall, pr);
//            }
          }
        });
  }

  JavascriptChannel _alertJavascriptChannel101() {
    return JavascriptChannel(
        name: 'gotoApp',
        onMessageReceived: (JavascriptMessage message) async {
          print(">>>>>>>>message${message.message}");
//          ClipboardData clipboardData = ClipboardData(text: message.message);
//          Clipboard.setData(clipboardData);
//          clearData();
          NaviUtil.push(context, TransitPaget());
        });
  }

  JavascriptChannel _alertJavascriptChannel102() {
    return JavascriptChannel(
        name: 'exitToLoginPage',
        onMessageReceived: (JavascriptMessage message) async {
          print(">>>>>>>>message${message.message}");
//          ClipboardData clipboardData = ClipboardData(text: message.message);
//          Clipboard.setData(clipboardData);
//          clearData();
//          NaviUtil.push(context, TransitPaget());
          NaviUtil.pushAndRemove(context, LoginWithPhone(false));
          SharedUtil.addStr(Constants.MEMBER_INFO, null);
        });
  }

  JavascriptChannel _alertJavascriptChannel103() {
    return JavascriptChannel(
        name: 'saveImg',
        onMessageReceived: (JavascriptMessage message) async {
          print(">>>>>>>>message${message.message}");
//          ClipboardData clipboardData = ClipboardData(text: message.message);
//          Clipboard.setData(clipboardData);
//          clearData();
//          NaviUtil.push(context, TransitPaget());
//          NaviUtil.pushAndRemove(context, LoginPage(false));
//          downloadOneImg(message.message);

          if (Platform.isAndroid) {
            PermissionStatus status =
                await PermissionUtil.requestPermission(Permission.storage);

            if (status == PermissionStatus.granted) {
              String path = await FileUtil.saveBase64toGallery1(message.message);
              if(path.isNotEmpty){
                toast("图片已保存");
              }else{
                toast("图片保存失败");
              }
            }
          } else {
            String path = await FileUtil.saveBase64toGallery1(message.message);
            if(path.isNotEmpty){
              toast("图片已保存");
            }else{
              toast("图片保存失败");
            }
          }
        });
  }

  //二维码
  void shareProductToSession() async {
    oneImgList.clear();

    if (linkEntity.codeImgUrl.isEmpty) {
      return;
    }
    String basicpath = "";
//    if(Platform.isAndroid){
    basicpath = (await FileUtil.findLocalPath(context)) +
        Constants.savePath;
//    }else{

//      basicpath = (await FileUtil)

//    }

    final savedDir = Directory(basicpath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".jpg";

    if (Platform.isAndroid) {
      PermissionStatus status =
          await PermissionUtil.requestPermission(Permission.storage);

      if (status == PermissionStatus.granted) {
        await pr.show();

        HttpUtils.downloadOneImg(linkEntity.codeImgUrl,
            basicpath + Platform.pathSeparator + fileName, shareOneImg, pr,saveToGallery: false);
      }
    } else {
      await pr.show();

      HttpUtils.downloadOneImg(linkEntity.codeImgUrl,
          basicpath + Platform.pathSeparator + fileName, shareOneImg, pr,saveToGallery: false);
    }
  }

  void downloadOneImg(String imgUrl) async {
    if (imgUrl.isEmpty) {
      return;
    }
    String basicpath = "";
//    if(Platform.isAndroid){
    basicpath = (await FileUtil.findLocalPath(context)) +
        Constants.savePath;
//    }else{

//      basicpath = (await FileUtil)

//    }

    final savedDir = Directory(basicpath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".jpg";

    if (Platform.isAndroid) {
      PermissionStatus status =
          await PermissionUtil.requestPermission(Permission.storage);

      if (status == PermissionStatus.granted) {
        await pr.show();

        await HttpUtils.downloadOneImg(linkEntity.codeImgUrl,
            basicpath + Platform.pathSeparator + fileName, downloadImg, pr);
        pr.hide();
      }
    } else {
      await pr.show();

      await HttpUtils.downloadOneImg(linkEntity.codeImgUrl,
          basicpath + Platform.pathSeparator + fileName, downloadImg, pr);

      pr.hide();
    }
  }

  void copyLink() {
    if (linkEntity.link.isNotEmpty) {
      ClipboardData data = new ClipboardData(text: linkEntity.link);
      Clipboard.setData(data);
      Fluttertoast.showToast(msg: "链接已复制");
    }
  }

  void copyRegisteryLink() {
    if (linkEntity.joinLink.isNotEmpty) {
      ClipboardData data = new ClipboardData(text: linkEntity.joinLink);
      Clipboard.setData(data);
      Fluttertoast.showToast(msg: "注册链接已复制");

      fluwxUtil.shareTextToSession(linkEntity.joinLink);
    }
  }

  void shareWebToSession() {
    fluwxUtil.shareLinkToSession(
        linkEntity.link, linkEntity.title, linkEntity.imgUrl, linkEntity.desc);
  }
  void shareInviteWebToSession() {
    fluwxUtil.shareLinkToSession(
        linkEntity.joinLink, linkEntity.customerSTitle, linkEntity.customerSImg, linkEntity.customerSDesc);
  }

  void clearData() {
    downloadNum = 0;
    finishNum.clear();
    path.clear();
    fileImageMap.clear();
  }

//  static void requestDownload(String url, String filename, String savePath,
//      Function downloadCallback) async {
//    await FlutterDownloader.enqueue(
//        url: url,
//        headers: {"auth": "test_for_sql_encoding"},
//        savedDir: savePath,
//        fileName: filename,
//        showNotification: true,
//        openFileFromNotification: true);
//  }

  void downloadCallBack() {
    pr.hide();
    Map map = Map();
//    if(path.length>1){
//      editList();
//    }
//    if(path.length==1){
//
//      for(int i=0;i<path.length;i++){
//        path[i]= path[i].split("jpg")[0]+"jpg";
//      }
//
//    }
//    Fluttertoast.showToast(msg: "downloadcall${path[0]}");
    map["imgs"] = path;
//    Fluttertoast.showToast(msg: "downloadcall${path.length}");


    if(notshare1){
      return;
    }

    if (path.length > 9) {
      Fluttertoast.showToast(
          msg: "下载成功，微信一次分享的图片应不大于9张~", toastLength: Toast.LENGTH_LONG);
    }
    if (path.length > 0 && path.length <= 9&&!notshare1) {
      fluwxUtil.share_mutiimg_wechat_system(map);
//      fluwxUtil.share_mutiimg_wechat_timeline(map);
    }
    if(sharevideo){
      Map map = Map();
      path.clear();
      path.add(videopath);
      map["video"] = map;
//      if (success) {
      File  file = new File(videopath);

      file.exists().then((value) {
        if(value){
          fluwxUtil.share_video(map);
        }
      });



    }

//    if(path.length==1){
//      Fluttertoast.showToast(msg: path[0]);
//      ClipboardData data = ClipboardData(text: path[0]);
//      Clipboard.setData(data);
//      print(path[0]);
//      fluwxUtil.shareLocalImgToSession(path[0]);
//    }
  }




  void editList() {
    path.sort((a, b) {
      return int.parse(a.split("jpg")[1])
          .compareTo(int.parse(b.split("jpg")[1]));
    });
//    List temp = List();
    for (String s in path) {
      s.substring(0, s.length - 1);
    }
    for (int i = 0; i < path.length; i++) {
      path[i] = path[i].split("jpg")[0] + "jpg";
    }
    for (String t in path) {
      print(t);
    }
  }

  void downloadVideoCall(bool success,{bool share}) {
    pr.hide();
    Map map = Map();
    map["video"] = path;
    if (success) {
      fluwxUtil.share_video(map);
    }
  }

  void downloadImg(bool success) {
    pr.hide();
  }

  JavascriptChannel _alertJavascriptChannel10() {
    return JavascriptChannel(
        name: 'shareProductToSession',
        onMessageReceived: (JavascriptMessage message) async {
          // toast("${message.message}");
          oneImgList.clear();
          print(message.message);

          if (message.message.isEmpty) {
            return;
          }
          String basicpath = (await FileUtil.findLocalPath(context)) +
              Platform.pathSeparator +
              "tDownload";
          final savedDir = Directory(basicpath);
          bool hasExisted = await savedDir.exists();
          if (!hasExisted) {
            savedDir.create();
          }
          String fileName =
              DateTime.now().millisecondsSinceEpoch.toString() + ".jpg";

          if (Platform.isAndroid) {
            PermissionStatus status =
                await PermissionUtil.requestPermission(Permission.storage);
            if (status == PermissionStatus.granted) {
              await pr.show();

              HttpUtils.downloadOneImg(
                  message.message,
                  basicpath + Platform.pathSeparator + fileName,
                  shareOneImg,
                  pr);
            }
          } else {
            await pr.show();

            HttpUtils.downloadOneImg(message.message,
                basicpath + Platform.pathSeparator + fileName, shareOneImg, pr);
          }
        });
  }

  List<String> oneImgList = List();
  void shareOneImg(String urlInGallery) {
    pr.hide();

    if (urlInGallery.isNotEmpty) {
      oneImgList.add(urlInGallery);
      Map map = Map();
      map["imgs"] = oneImgList;
      fluwxUtil.share_mutiimg_wechat_system(map);
    }
  }

  JavascriptChannel _alertJavascriptChannel6() {
    return JavascriptChannel(
        name: 'sendAvatarUrl',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");

          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel7() {
    return JavascriptChannel(
      name: 'loginflutter',
      onMessageReceived: (JavascriptMessage message) {
        print(">>>messagelogin");
        // toast("${message.message}");
        print(message.message);
      },
    );
  }

  JavascriptChannel _alertJavascriptChannel5() {
    return JavascriptChannel(
        name: 'wxpay',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(">>>${message.message}");
          try {
            Map<String, dynamic> map =
                JsonUtil.json2map(message.message.toString());

            print(">>>map${map["title"]}");
            WxpayEntity linkEntity = WxpayEntity.fromJson(map);
            fluwx
                .payWithWeChat(
                    appId: linkEntity.appid,
                    partnerId: linkEntity.partnerid,
                    packageValue: linkEntity.package,
                    nonceStr: linkEntity.noncestr,
                    timeStamp: int.parse(linkEntity.timestamp),
                    sign: linkEntity.sign,
                    prepayId: linkEntity.prepayid)
                .then((v) {
              controller
                  ?.evaluateJavascript('orderList("1")')
                  ?.then((result) {});

              print(v);
            });
          } catch (e) {
            print(">>>${e.toString()}");
          }
          setState(() {});
        });
  }

  Widget getTitle1(int index) {
    if (index == 0) {
      if (currentTab == index) {
        return Text("首页",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("首页",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
    if (index == 1) {
      if (currentTab == index) {
        return Text("分类",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("分类",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }

    if (index == 3) {
      if (currentTab == index) {
        return Text("购物车",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("购物车",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
    if (index == 4) {
      if (currentTab == index) {
        return Text("订单",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("订单",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
  }

  int count = 0;

  void setJpush() {
//    jpush.setup(appKey: "5e9832d602004a4d2314b09c" ,channel: 'developer-default');
    jpush.setup(
        appKey: "2e8bdbd95f93bd0acb678139",
        channel: 'theChannel',
        production: false,
        debug: true);
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    jpush.setBadge(0);
    jpush.getRegistrationID().then((v) {
      print("flutter 接收到推送: ${v}");
      if(v!=null){

      }

      postInfo(v.toString());

      // {alert: 发一个比较正常的消息, extras: {cn.jpush.android.ALERT_TYPE: -1, cn.jpush.android.NOTIFICATION_LARGE_ICON: https://file.91aplus.com/images_cb7362020070910533664701.png, cn.jpush.android.NOTIFICATION_ID: 520553338, cn.jpush.android.MSG_ID: 54043267412569096, cn.jpush.android.ALERT: 发一个比较正常的消息, cn.jpush.android.EXTRA: {}}, title: 正常的消息}
//          {link: https://a.91aplus.com, _j_business: 1, extras: {link: https://a.91aplus.com}, _j_uid: 41798158226, _j_msgid: 29273484846958197, aps: {alert: 321, badge: 2, sound: }}

    });
    // 监听jpush
    jpush.addEventHandler(
      onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter 接收到推送: ${message.toString()}");
        count++;
        jpush.setBadge(count);
      },
      onOpenNotification: (Map<String, dynamic> message) {
        String url = "";
        if (Platform.isAndroid) {
          ClipboardData clipboardData = ClipboardData(text: message.toString());
          Clipboard.setData(clipboardData);
          url =
              json.decode(message['extras']['cn.jpush.android.EXTRA'])['link'];
          controller.loadUrl(url);
//          Fluttertoast.showToast(msg: json.decode(message['extras']['cn.jpush.android.EXTRA'])['link']);
//          print((json.decode(message['extras']['cn.jpush.android.EXTRA'])['link']));
        }else{
          url = json.decode(message['extras'])['link'];
          controller.loadUrl(url);
        }

        print("flutter>>> open");
        // 点击通知栏消息，在此时通常可以做一些页面跳转等
        String string = message.toString();
        print("flutter>>> open1");
        List<String> s = string.split("<<<");
        print("flutter>>> open2");
        count > 0 ? count-- : count = 0;
        jpush.setBadge(count);
//        Fluttertoast.showToast(msg: "${message.toString()}");
//        Fluttertoast.showToast(msg: "${message["link"]}");
      },
    );
  }

  Widget getIcon1(int index) {
    if (index == 0) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 1) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c2.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g2.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 3) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c3-1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g3-1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 4) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          child: Stack(
            children: <Widget>[
              Container(
                width: 25,
                height: 25,
                alignment: Alignment.bottomCenter,
                child: Image.asset(
                  "assets/nMenu-c4.png",
                  width: 20.0,
                  height: 20.0,
                  fit: BoxFit.fill,
                ),
              ),
              Positioned(
                child: customBage(),
                right: 0,
                top: 0,
              )
            ],
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          child: Stack(
            children: <Widget>[
              Container(
                width: 25,
                height: 25,
                alignment: Alignment.bottomCenter,
                child: Image.asset(
                  "assets/nMenu-g4.png",
                  width: 20.0,
                  height: 20.0,
                  fit: BoxFit.fill,
                ),
              ),
              Positioned(
                child: customBage(),
                right: 0,
                top: 0,
              )
            ],
          ),
        );
      }
    }
  }

  Widget click() {
    if (currentTab != 2) {
      return Image.asset("assets/Group@3x.png");
    } else {
      return Image.asset("assets/Group1.png");
    }
  }

  Widget wrongPage() {
    //return conta
  }
//个人信息
  void postInfo(String rid) async {
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      MemberInfoEntity memberInfoEntity = Constants.memberInfoEntity;
      map["member_id"] = memberInfoEntity.data.memberId;
      map["registration_id"] = rid;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + '/member/rpush/index',
          data: map);

      print("${map1.toString()}");
//      Fluttertoast.showToast(msg: "${map1.toString()}");

      if (memberInfoEntity.code == null) {
        return;
      }

      if (memberInfoEntity.code == 200) {}
    } catch (e) {
      print(e.toString());
    } finally {
      print(">>>>>finally111111");
    }
  }
}
